package org.example.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务socket
 */
public class SocketServer {
    public static void main(String[] args) throws IOException {
        //从端口创建ServerSocket
        try (ServerSocket serverSocket = new ServerSocket(10040)) {
            System.out.println("tcp服务启动成功,端口为10040");
            //客户端数量
            int count = 0;
            //此处有阻塞,故使用死循环即可
            while (!serverSocket.isClosed()) {
                //侦听并接收的客户端Socket
                Socket socket = serverSocket.accept();
                System.out.println("客户端已连接,信息为" + socket);
                //新线程运行Socket
                new Thread(() -> {
                    try {
                        //如socket未关闭,则始终循环,read方法会阻塞线程故死循环即可
                        while (!socket.isClosed()) {
                            //缓存字节数组
                            byte[] b = new byte[1024];
                            System.out.println("等待读取数据");
                            //将输入流读入缓存
                            int r = socket.getInputStream().read(b);
                            if (r > -1) {
                                //接收转换后的字符串
                                String data = new String(b, 0, r);
                                System.out.println("获取到字符串:" + data);
                                //响应客户端请求
                                OutputStream outputStream = socket.getOutputStream();
                                outputStream.write("ok".getBytes());
                                System.out.println("发送数据:ok");
                                //清空缓冲区数据
                                outputStream.flush();
                            } else {
                                socket.close();
                                System.out.println("input流发送异常,socket被远程关闭,线程结束");
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                //记录客户端数量
                count++;
                System.out.println(("客户端数量" + count));
            }
        }
    }
}
